const app = getApp();

Page({
  data: {
    id: null,
    schedule: null,
    selectedSeat: null,
    paymentMethod: 'WECHAT',
    loading: false
  },
  
  onLoad: function(options) {
    const id = options.id;
    if (!id) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    this.setData({
      id: id
    });
    
    // 检查登录状态
    if (!app.globalData.token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 加载班车详情
    this.loadScheduleDetail();
  },
  
  // 加载班车详情
  loadScheduleDetail: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    app.request({
      url: `/schedules/${this.data.id}`
    }).then(data => {
      wx.hideLoading();
      this.setData({
        schedule: data
      });
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message || '加载失败',
        icon: 'none'
      });
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    });
  },
  
  // 选择座位
  selectSeat: function(e) {
    const seat = e.currentTarget.dataset.seat;
    this.setData({
      selectedSeat: seat
    });
  },
  
  // 选择支付方式
  selectPaymentMethod: function(e) {
    const method = e.currentTarget.dataset.method;
    this.setData({
      paymentMethod: method
    });
  },
  
  // 提交预约
  submitReservation: function() {
    const { schedule, selectedSeat, paymentMethod } = this.data;
    
    // 检查是否可预约
    if (schedule.availableSeats <= 0) {
      wx.showToast({
        title: '该班车已满，无法预约',
        icon: 'none'
      });
      return;
    }
    
    // 检查是否选择了座位
    if (!selectedSeat) {
      wx.showToast({
        title: '请选择座位',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    wx.showLoading({
      title: '提交中...',
    });
    
    app.request({
      url: '/reservations',
      method: 'POST',
      data: {
        scheduleId: schedule.id,
        seatNumber: selectedSeat,
        paymentMethod: paymentMethod
      }
    }).then(data => {
      wx.hideLoading();
      this.setData({
        loading: false
      });
      
      wx.showToast({
        title: '预约成功',
        icon: 'success'
      });
      
      // 跳转到我的预约页面
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/my-reservations/my-reservations',
        });
      }, 1500);
    }).catch(err => {
      wx.hideLoading();
      this.setData({
        loading: false
      });
      
      wx.showToast({
        title: err.message || '预约失败',
        icon: 'none'
      });
    });
  },
  
  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
}) 